package com.tangkun.environment.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tangkun.environment.R;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CropImageView;

import java.io.IOException;

/**
 * 移动和缩放
 */
public class CropImageActivity extends BaseActivity {
    private ImageView cropback;
    private TextView cropsure;
    private CropImageView cropimage;
    public static final int RESULT_IMAGE_TOO_SMALL = 1;

    private int activity_ret = RESULT_OK;
    private Drawable drawable;
    private String temppath;

    // 图片最小宽高限制
    private static final int IMG_MIN_W = 360;
    private static final int IMG_MIN_H = 360;

    // 上传服务器图片宽高限制，大于640取640，在360-640之间取360
    private static int IMG_UPLOAD_W = 640;
    private static int IMG_UPLOAD_H = 640;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cropimage);
        temppath = getIntent().getStringExtra("uri");
        initView();
    }

    private void initView() {
        cropback = (ImageView) findViewById(R.id.back);
        cropsure = (TextView) findViewById(R.id.next);
        TextView textView = (TextView) findViewById(R.id.title);
        textView.setText("移动和缩放");
        cropsure.setText("确定");
        cropsure.setVisibility(View.VISIBLE);
        cropimage = (CropImageView) findViewById(R.id.cropimage);
        Bitmap bitmap = loadBitmap(temppath);
        if (bitmap == null) {
            finish();
            return;
        }
        drawable = new BitmapDrawable(bitmap);
        cropimage.setDrawable(drawable, 240, 240);
        cropsure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        Bitmap bitmap = cropimage.getCropImage(IMG_UPLOAD_W, IMG_UPLOAD_H);
                        if (bitmap == null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    Toast.makeText(getApplicationContext(), "内存不足，请重试", Toast.LENGTH_LONG).show();
                                }
                            });
                            return;
                        }
                        showToast("返回bitmap：" + (bitmap == null));
                        String str = Utils.bitmapToFile(getApplicationContext(), bitmap, 80);
//                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                        bitmap.compress(CompressFormat.JPEG, 80 /* ignored for JPEG */, bos);
                        Intent intent = new Intent();
                        intent.putExtra("backurl", str);
                        LogUtils.e("图片地址1：" + str);
//                        intent.putExtra("backurl", bitmap);
                        setResult(activity_ret, intent);
                        finish();
                    }
                }).start();

            }
        });

        cropback.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });
    }

    private Bitmap loadBitmap(String imgpath) {
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(imgpath);
        } catch (IOException e) {
            e.printStackTrace();
            exif = null;
        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 1;
        opts.inJustDecodeBounds = true;
        try {
            BitmapFactory.decodeFile(imgpath, opts);
        } catch (OutOfMemoryError e) {
            // TODO: handle exception
            return null;
        }

        // 上传图片最小宽度和高度限制
        if (opts.outWidth < IMG_MIN_W || opts.outHeight < IMG_MIN_H) {
            Toast.makeText(getApplicationContext(), "图片过小不能作为头像哦", Toast.LENGTH_LONG).show();
            return null;
        }

        // 上传图片宽高介于480-640之间，上传图片宽高置都为480
        if ((opts.outWidth >= IMG_MIN_W && opts.outWidth < IMG_UPLOAD_W) || (opts.outHeight >= IMG_MIN_H && opts.outHeight < IMG_UPLOAD_H)) {
            IMG_UPLOAD_W = IMG_MIN_W;
            IMG_UPLOAD_H = IMG_MIN_H;
        }

        // 防止打开超大的图，导致后续内容容易溢出
        if (opts.outWidth >= IMG_MIN_W * 2.5f && opts.outHeight >= IMG_MIN_H * 2.5f) {
            opts.inSampleSize = 2;
        }

        Bitmap bitmap = null;
        opts.inJustDecodeBounds = false;
        boolean flag = false;
        // 循环遍历10次中解码图片失败，防止一直没有内存导致死循环
        int retryCount = 0;
        while (flag == false && retryCount < 10) {
            try {
                bitmap = BitmapFactory.decodeFile(imgpath, opts);
                flag = true;
            } catch (OutOfMemoryError e) {
                // TODO: handle exception
                opts.inSampleSize += 1;
                retryCount++;
                flag = false;
                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }
                System.gc();
            }
        }
        // 解码图片时候，降低图片质量10次都内存溢出了给个提示
        if (flag = false) {
            Toast.makeText(getApplicationContext(), "亲！你手机内存不足啦，建议您清理下手机内存噢", Toast.LENGTH_LONG).show();
            return null;
        }

        int digree = 0;
        if (exif != null) {
            int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            switch (ori) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    digree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    digree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    digree = 270;
                    break;
                default:
                    digree = 0;
                    break;
            }
        }
        // tangkun 这里bitmap可能报空指针
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (digree != 0) {
            // 旋转图片
            flag = false;
            Bitmap newBitmap = null;
            Matrix m = new Matrix();
            m.postRotate(digree);
            int retrycnt = 0;
            while (!flag && retrycnt < 5) {
                try {
                    newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
                    flag = true;
                    bitmap.recycle();
                    bitmap = newBitmap;
                } catch (OutOfMemoryError e) {
                    flag = false;
                    retrycnt++;
                    System.gc();
                }
            }
        }
        return bitmap;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    protected void onPuase() {
        super.onPause();
    }
}
